import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_table/flutter_html_table.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/home/news_item_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:sports_new/widgets/picture_preview_widget.dart';

import '../../widgets/base/qkd_text.dart';

class ZixunDetailView extends StatelessWidget {
  final NewsItemEntity? data;
  const ZixunDetailView({this.data, super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(bottom: 20),
      decoration: const BoxDecoration(
        color: Colours.white,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 14),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: QkdText(data?.title ?? '',
              fontSize: 22,
              fontWeight: FontWeight.w500
            ),
          ),
          const SizedBox(height: 8),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: QkdText(data?.publishTime ?? '',
              color: Colours.grey99, fontSize: 12
            ),
          ),
          const SizedBox(height: 16),
          Html(
            data: getData(),
            extensions: [
              TableHtmlExtension(),
              TagExtension(
                  tagsToExtend: {"img"},
                  builder: (extensionContext) {
                    final e = extensionContext.styledElement;
                    return GestureDetector(
                      onTap: () => Get.dialog(PicturePreview(imageUrl: e?.attributes['src'] ?? ""),
                          useSafeArea: false),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: CachedNetworkImage(
                          imageUrl: e?.attributes['src'] ?? "",
                          width: Get.width,
                          fit: BoxFit.cover,
                          placeholder: (context,url) => Container(),
                          errorWidget: (context,url,error) => Container(),
                        ),
                      ),
                    );
                  }
              ),
            ],
            style: {
              "body": Style(letterSpacing: -0.5),
              "p": Style(margin: Margins.all(0)),
              "matchLabel": Style(margin: Margins.all(0)),
              "img": Style(
                  width: Width(Get.width - 40),
                  margin: Margins.zero,
                  height: Height.auto(),
                  display: Display.block,
                  textAlign: TextAlign.center),
              ".content": Style(
                  padding: HtmlPaddings.zero,
                  // backgroundColor: Colors.green,
                  margin: Margins.zero),
              "#wholeBody": Style(
                  margin: Margins.only(left: 20, right: 20, top: 8, bottom: 6)),
              "#publishInfo": Style(
                  fontSize: FontSize(14),
                  color: Colours.grey99,
                  textAlign: TextAlign.left,
                  margin: Margins.only(top: 8)),
              "#article": Style(
                  color: Colours.text,
                  margin: Margins.all(0),
                  fontSize: FontSize(18),
                  letterSpacing: -0.6,
                  lineHeight: const LineHeight(1.6),
                  whiteSpace: WhiteSpace.normal,
                  textAlign: TextAlign.justify),
              "#reprint": Style(
                  fontSize: FontSize(12),
                  // backgroundColor: Colors.brown,
                  color: Colours.grey99,
                  textAlign: TextAlign.justify,
                  fontWeight: FontWeight.w300,
                  margin: Margins.only(bottom: 8)),
              "#claim": Style(
                  fontSize: FontSize(12),
                  // backgroundColor: Colors.pinkAccent,
                  color: Colours.grey99,
                  lineHeight: const LineHeight(1.4),
                  textAlign: TextAlign.justify,
                  fontWeight: FontWeight.w300),
            },
          ),
        ],
      ),
    );
  }

  String getData() {
    var regC = RegExp(r"[\u4e00-\u9fa5]");
    var regCom = RegExp(r'<\/p>[.\n\s]*<p>');
    var regP = RegExp(r'\/>[.\n\s]*<p>');
    var regImg = RegExp(r'\/>[.\n\s]*<img');
    var regInLine = RegExp(r'<p[^<>]*>[^<>]+<img');
    // Document document = parse(data?.content ?? "");
    String append = '';
    String? com = data?.content?.splitMapJoin(regInLine, onMatch: (match) {
      var result = match[0]?.split("<img").join("</p><p><img") ?? "";
      return result;
    });
    // .split(RegExp(r"<[br \/]+>")).join("")
    com = com?.replaceAllMapped(RegExp(r"""<span class="img">(.*?)<\/span>"""),
        (match) => match.group(1)!);
    com = com
            ?.split("<p>&nbsp;</p>")
            .join("<div style= 'height: 8;width: 200px;'>  </div>")
            .split(regCom)
            .join("</p><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regP)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><p>")
            .split(regImg)
            .join("/><div style= 'height: 8;width: 200px;'>  </div><img")
            .split('src=" ')
            .join('src="')
        // .split(regBody)
        // .join("/p><div style= 'height: 25;width: 200px;'>  </div></body")
        ??
        "";
    log(com);
    com.split("").forEach((element) {
      if (regC.hasMatch(element)) {
        append += "$element\u200A";
      } else {
        append += element;
      }
    });

    var newData = "";
    newData = "<body id='wholeBody'>"
        "<div id='article'>$append</div>"
        "<div style= 'height: 24px;width: 200px;'>  </div>"
        "${data?.hrefList == null ? "" : "<matchLabel> </matchLabel>"}"
        "${data?.media == null || data?.media == '' ? '' : "<p id='reprint'>${'转\u200A载\u200A自\u200A：\u200A${data?.media?.split('').join("\u200A")}'}</p>"}"
        "<p id='claim'>${data?.disclaimer?.split('').join("\u200A") ?? ''}</p>"
        "</body>";
    return newData;
  }

  Widget labelCell(HrefItem item) {
    Widget cell = Container();
    switch (item.type) {
      case 1:
        List<String> name = item.name?.split(",") ?? [];
        List<String> logo = item.logo?.split(",") ?? [];
        cell = Row(
          mainAxisSize: MainAxisSize.min,
          children: List.generate(
              2,
              (index) => infoCell(
                  logo.length - 1 < index ? "" : logo[index],
                  name.length - 1 < index ? "" : name[index],
                  index == 1)).insertWith(1, [
            Image.asset(width: 16, Utils.getImgPath("news_vs.png"))
                .paddingSymmetric(horizontal: 6)
          ]),
        );
        break;
      default:
        cell = infoCell(item.logo, item.name, false);
    }
    return GestureDetector(
      onTap: () {
        switch (item.type) {
          case 1:
            Get.toNamed(Routes.zqMatchDetail, arguments: item.extId);
            break;
          case 2:
            Get.toNamed(Routes.leagueDetail,
                arguments: item.extId.toString(),
                parameters: {"type": "0", "index": "0"});
            break;
          case 3:
            Get.toNamed(Routes.zqTeamDetail, arguments: item.extId);
            break;
        }
      },
      child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
              color: Colours.greyF7, borderRadius: BorderRadius.circular(4)),
          child: cell),
    );
  }

  Widget infoCell(String? logo, String? name, bool reverse) {
    List<Widget> list = [
      QkdImage(imageUrl: logo, width: 16, height: 16),
      Container(width: 4),
      QkdText(name ?? "",fontSize: 12)
    ];
    if (reverse) list = list.reversed.toList();
    return Row(mainAxisSize: MainAxisSize.min, children: list);
  }
}
